package com.jushu.storbox.network;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.util.LogUtil;

/**
 * 
 * wifi controller
 * 
 */
public class WifiController extends ContextWrapper {
	private static final String TAG = "WifiController";
	private int status;

	public WifiController(Context context) {
		super(context);
	}

	/**
	 * judge 3G or wifi state
	 * 
	 * @return boolean true:wifi, false:3G
	 */
	public void is3GorWifi() {
		LogUtil.i(TAG, "is3GorWifi");
		String is3G = ClientConfig.NETWORK_IS_NOT_AVAILIBLE;
		SharedPreferences settings = getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		Editor editor = settings.edit();
		NetworkInfo networkInfo = getNetworkInfo();
		int type = -1;
		if (null != networkInfo) {
			type = networkInfo.getType();
			if (0 == type) {
				is3G = ClientConfig.NETWORK_IS3G;
			} else if (1 == type) {
				is3G = ClientConfig.NETWORK_ISWIFI;
			} else {
				is3G = ClientConfig.NETWORK_IS_NOT_AVAILIBLE;
			}
		}
		editor.putString(ClientConfig.IS3GWIFI, is3G);
		editor.commit();
	}

	/**
	 * wifi type
	 * 
	 * @return boolean true: 3G ; false: wifi
	 */
	public String getWifiType() {
		SharedPreferences settings = getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		String is3G = settings.getString(ClientConfig.IS3GWIFI,
				ClientConfig.NETWORK_IS_NOT_AVAILIBLE);
		return is3G;
	}

	/**
	 * netWork information
	 * 
	 * @return
	 */
	public NetworkInfo getNetworkInfo() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		return networkInfo;
	}

	/**
	 * obtain network state
	 * 
	 * @return
	 */
	public boolean networkIsAvailible() {
		SharedPreferences settings = getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		Editor editor = settings.edit();
		boolean isAvailible = false;
		NetworkInfo networkInfo = getNetworkInfo();
		if (null != networkInfo && networkInfo.isAvailable()) {
			isAvailible = true;
		}
		editor.putBoolean(ClientConfig.INTERNETSTATE, isAvailible);
		editor.commit();
		return isAvailible;
	}

	/**
	 * whether network is availible
	 * 
	 * @return
	 */
	public boolean getNetworkState() {
		SharedPreferences settings = getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		boolean isAvailible = false;
		if(!settings.contains(ClientConfig.INTERNETSTATE)) {
			NetworkInfo networkInfo = getNetworkInfo();
			if (null != networkInfo && networkInfo.isAvailable()) {
				isAvailible = true;
			}
			Editor editor = settings.edit();
			editor.putBoolean(ClientConfig.INTERNETSTATE, isAvailible);
			editor.commit();
		} else {
			isAvailible = settings.getBoolean(ClientConfig.INTERNETSTATE,
					false);
		}
		return isAvailible;
	}

	/**
	 * internet enable, browser not found weblink, if return code is
	 * 
	 * @return boolean true:internet enable, false:internet disable
	 */
	public boolean accessToInternet() {
		String server = ClientConfig.HTTP_INTERNET_DOMAIN;
		boolean internetState = false;
		URL url = null;
		HttpURLConnection conn = null;
		try {
			url = new URL(server);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(1000);
			conn.setReadTimeout(3000);
			if (404 == conn.getResponseCode()) {
				internetState = true;
			} else {
				internetState = false;
			}
		} catch (MalformedURLException e) {
			// Auto-generated catch block
			e.printStackTrace();
			internetState = false;
		} catch (IOException e) {
			// Auto-generated catch block
			e.printStackTrace();
			internetState = false;
		} catch (IllegalArgumentException e) {// connect/read/timeout
			// TODO: handle exception
			e.printStackTrace();
			internetState = false;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			internetState = false;
		}
		LogUtil.i(TAG, "show internet state:" + internetState);
		return internetState;
	}

	public boolean isWifiConnected() {
		return getNetWord() == 1;
	}

	public int getNetWord() {
		SharedPreferences settings = getSharedPreferences(
				ClientConfig.settings, Context.MODE_APPEND);
		Editor eidtor = settings.edit();
		
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isAvailable()
				&& networkInfo.isConnected()) {
			if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI
					&& networkInfo.getState() == State.CONNECTED) {
				eidtor.putString(ClientConfig.IS3GWIFI, ClientConfig.NETWORK_ISWIFI);
				status = 1;
			} else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET
					&& networkInfo.getState() == State.CONNECTED) {
				eidtor.putString(ClientConfig.IS3GWIFI, ClientConfig.NETWORK_IS3G);
				status = 2;
			} else {
				eidtor.putString(ClientConfig.IS3GWIFI, ClientConfig.NETWORK_IS_NOT_AVAILIBLE);
				status = 3;
			}
		} else {
			eidtor.putString(ClientConfig.IS3GWIFI, ClientConfig.NETWORK_IS_NOT_AVAILIBLE);
			status = 0;
		}
		eidtor.commit();
		return status;
	}

	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& (inetAddress instanceof Inet4Address)) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return null;
	}
}
